﻿//LookUp Manager ver.2.0
//Fully DBPUX instruction set compliant.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using CodeDynamiksEngine;
using MESCodeFile;

namespace mes_tublay
{
    public partial class frmLookUpManager : Form
    {
        CodeProcessor proc = new CodeProcessor(ThreadingMode.Normal);
        DataCache dat = new DataCache("myData");
        CodeScript script;

        bool isAdding = true;
        int curDat = -1;
        
        public frmLookUpManager()
        {
            InitializeComponent();
            InitializeFrameSliderForm();
        }
        private void InitializeForm()
        {
            label4.Text = "Tips :\r\n" +
                "- You can select a key on the drop down list provided.\r\n" +
                "- You can add new keys by typing the new key in the drop down list text field.\r\n" +
                "- Add new data to key at the Add/Edit Box.\r\n" +
                "- Edit a data by double clicking the data and make modification at the Add/Edit Box.\r\n" +
                "- Click the Confirm button to apply the changes.";
            DoEvents();
            LoadKeys();
            proc.ProcessCompleted += new EventHandler(proc_ProcessCompleted);
        }

        void proc_ProcessCompleted(object sender, EventArgs e)
        {
            proc.SafeCall(this, delegate
            {
                if (proc.State == ProcessorFlag.Error ||
                    proc.State == ProcessorFlag.DataRdyErr ||
                    proc.State == ProcessorFlag.ReadyErr)
                {
                    MessageBox.Show(proc.GetProcessorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                switch (proc.GetLastProcessName().ToString())
                {
                    case "GETKEYS":
                        proc.DataFetch(out dat);
                        dat.SetActivePage(0);

                        txtKey.Items.Clear();
                        txtKey.Items.AddRange(dat.GetStringList(0));//keys[0].ToList(0));
                        States(true);
                        break;
                    case "DELETE":
                    case "GETDATA":
                    case "COMMIT":
                        proc.DataFetch(out dat);

                        dat.SetActivePage(0);
                        grdList.DataSource = dat.ExportPage();
                        grdList.Columns[0].Width = (grdList.Width * 90)  / 100;

                        dat.SetActivePage(2);
                        txtKey.Items.Clear();
                        txtKey.Items.AddRange(dat.GetStringList(0));//keys[0].ToList(0));

                        States(true);
                        break;
                        /*
                        proc.DataFetch(out dat);
                        dat.SetActivePage(0);
                        grdList.DataSource = dat.ExportPage();
                        grdList.Columns[0].Width = (grdList.Width * 90)  / 100;
                        States(true);
                        break;
                         */
                }
            });
        }
        void getData()
        {
            //Check if the processor is executing script, if it is, return to the calling code.
            if (proc.State != ProcessorFlag.Ready && proc.State != ProcessorFlag.DataRdy) return;

            script = new CodeScript("GETDATA");
            script.Add(CodeIns.SYS_RESET);
            script.Add(CodeIns.DBU_NEW_CORE);
            script.Add(CodeIns.DBU_CONNECT, Common.CFG.Read("DRIVER"), Common.CFG.Read("DB"),
                        Common.CFG.Read("UID"), Common.CFG.Read("PWD"), Common.CFG.Read("SERVER"));
            script.Add(CodeIns.DBU_BEGIN_TRANSACTION);
            script.Add(CodeIns.DBU_QUERY, string.Format("SELECT fData AS 'Data Value' FROM tbllookup WHERE fKey='{0}' ORDER BY fData ASC", txtKey.Text));
            script.Add(CodeIns.DBU_QUERY, string.Format("SELECT fID, fKey, fData, fStamp FROM tbllookup WHERE fKey='{0}' ORDER BY fData ASC", txtKey.Text));
            script.Add(CodeIns.DBU_QUERY, "SELECT DISTINCT fKey FROM tbllookup ORDER BY fKey ASC");
            script.Add(CodeIns.DBU_END);
            proc.Run(script);
        }

        void DoEvents()
        {
            txtKey.SelectedIndexChanged += new EventHandler(delegate
            {
                States(false);
                getData();
            });
            btnCancel.Click += new EventHandler(delegate
            {
                States(true);
                btnCancel.Enabled = false;
                txtData.Text = "";
                isAdding = true;
            });
            btnDelete.Click += new EventHandler(delegate
            {
                if (grdList.SelectedRows.Count > 0)
                {
                    DialogResult dlg = MessageBox.Show("The selected data will be permanently deleted. Do you wish to continue?",
                                "LookUp Manager", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
                    if (dlg == System.Windows.Forms.DialogResult.No) return;
                    
                    States(false);
                    curDat = grdList.SelectedRows[0].Index;
                    
                    dat.SetActivePage(1);
                    script = new CodeScript("DELETE");
                    script.Add(CodeIns.SYS_RESET);
                    script.Add(CodeIns.DBU_NEW_CORE);
                    script.Add(CodeIns.DBU_CONNECT, Common.CFG.Read("DRIVER"), Common.CFG.Read("DB"),
                        Common.CFG.Read("UID"), Common.CFG.Read("PWD"), Common.CFG.Read("SERVER"));
                    script.Add(CodeIns.DBU_BEGIN_TRANSACTION);
                    script.Add(CodeIns.DBU_DELETE, "tbllookup", string.Format("(fID='{0}') AND (fStamp='{1}')", dat.GetValue(curDat, "fID"), Helper.ToMySQLDateTime(dat.GetValue(curDat, "fStamp"))));
                    script.Add(CodeIns.DBU_QUERY, string.Format("SELECT fData AS 'Data Value' FROM tbllookup WHERE fKey='{0}' ORDER BY fData ASC",
                        txtKey.Text)
                        );
                    script.Add(CodeIns.DBU_QUERY, string.Format("SELECT fID, fKey, fData, fStamp FROM tbllookup WHERE fKey='{0}' ORDER BY fData ASC",
                        txtKey.Text)
                        );
                    script.Add(CodeIns.DBU_QUERY, "SELECT DISTINCT fKey FROM tbllookup ORDER BY fKey ASC");
                    script.Add(CodeIns.DBU_END);
                    proc.Run(script);
                }
            });
            grdList.DoubleClick += new EventHandler(delegate
            {
                if (grdList.SelectedRows.Count > 0)
                {
                    isAdding = false;
                    btnCancel.Enabled = true;
                    curDat = grdList.SelectedRows[0].Index;
                    txtData.Text = grdList.SelectedRows[0].Cells[0].Value.ToString();
                    txtData.Focus();
                    txtData.SelectionStart = txtData.Text.Length;
                    grpLookup.Enabled = false;
                }
            });
            btnCommit.Click += new EventHandler(delegate
            {
                bool isValid = true;
                if (txtKey.Text.Length == 0) isValid = false;
                if (txtData.Text.Length == 0) isValid = false;
                if (!isValid)
                {
                    MessageBox.Show("Invalid inputs detected!",
                   "LookUp Manager", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                States(false);

                //Check if the processor is executing script, if it is, return to the calling code.
                if (proc.State != ProcessorFlag.Ready && proc.State != ProcessorFlag.DataRdy) return;

                script = new CodeScript("COMMIT");
                script.Add(CodeIns.SYS_RESET);
                script.Add(CodeIns.DBU_NEW_CORE);
                script.Add(CodeIns.DBU_CONNECT, Common.CFG.Read("DRIVER"), Common.CFG.Read("DB"),
                        Common.CFG.Read("UID"), Common.CFG.Read("PWD"), Common.CFG.Read("SERVER"));
                script.Add(CodeIns.DBU_BEGIN_TRANSACTION);

                if (isAdding)
                {
                    script.Add(CodeIns.DBU_INSERT, "tbllookup", new string[] { "fKey", "fData" }, new object[] { "'" + txtKey.Text.ToUpper().Trim() + "'", "'" + txtData.Text.Trim() + "'" });
                }
                else
                {
                   
                    dat.SetActivePage(1);
                    script.Add(CodeIns.DBU_UPDATE, "tbllookup", new string[]{"fKey", "fData"}, new object[] {"'" + txtKey.Text.ToUpper().Trim() + "'", "'" + txtData.Text.Trim() + "'"},
                        string.Format("(fID='{0}') AND (fStamp='{1}')", dat.GetValue(curDat, "fID"), Helper.ToMySQLDateTime(dat.GetValue(curDat, "fStamp"))));
                    
                }

                script.Add(CodeIns.DBU_QUERY, string.Format("SELECT fData AS 'Data Value'FROM tbllookup WHERE fKey='{0}' ORDER BY fData ASC", txtKey.Text));
                script.Add(CodeIns.DBU_QUERY, string.Format("SELECT fID, fKey, fData, fStamp FROM tbllookup WHERE fKey='{0}' ORDER BY fData ASC", txtKey.Text));
                script.Add(CodeIns.DBU_QUERY, "SELECT DISTINCT fKey FROM tbllookup ORDER BY fKey ASC");

                script.Add(CodeIns.DBU_END);
                txtData.Text = "";
                proc.Run(script);

            });
        }

        void States(bool state)
        {
            grpAddEditBox.Enabled = state;
            grpLookup.Enabled = state;
            pnlWait.Visible = !state;
        }
        void LoadKeys()
        {
            States(false);
            //Check if the processor is executing script, if it is, return to the calling code.
            if (proc.State != ProcessorFlag.Ready && proc.State != ProcessorFlag.DataRdy) return;

            script = new CodeScript("GETKEYS");
            script.Add(CodeIns.SYS_RESET);
            script.Add(CodeIns.DBU_NEW_CORE);
            script.Add(CodeIns.DBU_CONNECT, Common.CFG.Read("DRIVER"), Common.CFG.Read("DB"),
                        Common.CFG.Read("UID"), Common.CFG.Read("PWD"), Common.CFG.Read("SERVER"));
            script.Add(CodeIns.DBU_BEGIN_TRANSACTION);
            script.Add(CodeIns.DBU_QUERY, "SELECT DISTINCT fKey FROM tbllookup ORDER BY fKey ASC");
            script.Add(CodeIns.DBU_END);
            proc.Run(script);
        }
     
    }
        
}
